package pers.corvey.studyjava.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pers.corvey.studyjava.dao.CourseCategoryDAO;
import pers.corvey.studyjava.dao.CourseDAO;
import pers.corvey.studyjava.exception.BadRequestException;
import pers.corvey.studyjava.exception.NotFoundException;
import pers.corvey.studyjava.model.Course;

@Service
public class CourseService {

    @Autowired
    private CourseDAO courseDAO;
    
    @Autowired
    private CourseCategoryDAO courseCategoryDAO;
    
    public Iterable<Course> getByCategoryId(String categoryId) {
        if (!courseCategoryDAO.exists(categoryId)) {
            throw new NotFoundException("该课程分类不存在！");
        }
        return courseDAO.findByCategoryId(categoryId);
    }
    
    public Course getCourseById(String id) {
        Course course = courseDAO.findOne(id);
        if (course == null) {
            throw new NotFoundException("该课程不存在！");
        }
        return course;
    }
    
    public Course createCourse(Course course) {
        if (!courseCategoryDAO.exists(course.getCategoryId())) {
            throw new NotFoundException("操作失败，该课程分类不存在！");
        }
        course.setGmtCreate(new Date());
        course.setGmtModified(new Date());
        return courseDAO.save(course);
    }
    
    public Course updateCourse(Course course) {
        if (!courseDAO.exists(course.getId())) {
            throw new BadRequestException("操作失败，不存在相应课程记录！");
        }
        if (!courseCategoryDAO.exists(course.getCategoryId())) {
            throw new BadRequestException("操作失败，该课程分类不存在！");
        }
        course.setGmtModified(new Date());
        return courseDAO.save(course);
    }
    
    public void deleteCourseById(String id) {
        courseDAO.delete(id);
    }
    
}
